/*
 * @Author: your name
 * @Date: 2022-03-09 16:52:21
 * @LastEditTime: 2022-04-27 03:30:16
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \vue-admin-template\src\store\modules\user.js
 */
import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken, setUserInfoCookie, setRoutesSession, removeUserInfoCookie, removeRoutesSession } from '@/utils/auth'
import { getFindMenus } from '@/api/role'
import parseMenu from '@/router/module/dynamicMenu'
import { buildTree } from '@/router/module/global'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: {},
    menus: [],
    role: {},
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLE: (state, role) => {
    state.role = role
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        commit('SET_TOKEN', response.token)
        setToken(response.token)
        resolve(response.token)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const data = response.data
        commit('SET_USERINFO', data)
        commit('SET_NAME', data.realname)
        commit('SET_AVATAR', data.avatar)
        commit('SET_ROLE', data.role)
        setUserInfoCookie(data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  Menus({ commit }, id) {
    return new Promise((resolve, reject) => {
      getFindMenus(id).then(response => {
        const data = response.data.privileges
        const accessRoutes = parseMenu(buildTree(data))
        setRoutesSession(accessRoutes)
        commit('SET_MENUS', accessRoutes)
        resolve(accessRoutes)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      removeRoutesSession()
      removeUserInfoCookie()
      // must remove  token  first
      commit('RESET_STATE')
      // commit('SET_MENUS', [])
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

